from datetime import datetime

import sqlalchemy
from flask import Blueprint, jsonify, request, session
from sqlalchemy import func, cast, or_

from exts import mail, db
from server.resource.util.MD5 import md5_encrypt,md5_verify
from models import EmailCaptchaaModel, UserModel, IncomeModel, TestRecord, TestReport
from server.resource.util.ApiResponse import ApiResponse
from flask_mail import Message
import string
import random

bp = Blueprint("manager",__name__,url_prefix="/manager")

@bp.route("/getTestRecordByMessage",methods=['POST'])
def getTestRecordByMessage():
    # 获取请求参数
    data = request.get_json()
    username = data.get('username')
    checkPerson = data.get('checkPerson')
    state = data.get('state')
    page = data.get('page')
    per_page = data.get('per_page')

    # 构建查询
    query = TestRecord.query.filter_by(is_delete=False)
    # 根据存在的参数构建查询条件
    if username:
        query = query.filter(TestRecord.username.ilike(f'%{username}%'))
    if checkPerson:
        print(checkPerson)
        query = query.filter(TestRecord.checkPerson.ilike(f'%{checkPerson}%'))
    if state:
        query = query.filter(TestRecord.state.ilike(f'%{state}%'))


    # 进行分页查询
    pagination = query.order_by(TestRecord.id).paginate(page=page, per_page=per_page, error_out=False)

    # 获取分页数据
    items = pagination.items

    # 构造响应数据
    response_data = {
        'page': pagination.page,
        'per_page': pagination.per_page,
        'total': pagination.total,
        'pages': pagination.pages,
        'data': [item.to_dict() for item in items]  # 假设有一个to_dict方法来准备数据
    }

    return jsonify(ApiResponse.success(response_data))

@bp.route("/send",methods=['POST'])
def send():
    data = request.get_json()
    id = data['id']
    test_record =TestRecord.query.filter_by(id = id).first()
    if not test_record:
        return jsonify(ApiResponse.server_error("没有该记录"))
    test_record.state = True
    test_record.checkPerson = 'admin1'
    # test_record.checkPerson = session['username']

    db.session.commit()

    return jsonify(ApiResponse.success())


@bp.route("/deleteTest",methods=['POST'])
def deleteTest():
    data = request.get_json()
    id = data['id']
    test_record =TestRecord.query.filter_by(id = id,is_delete=False).first()
    if not test_record:
        return jsonify(ApiResponse.server_error("没有该记录"))
    test_record.is_delete = True
    test_report = TestReport.query.filter_by(id= test_record.TestReport_id).first()
    test_report.is_delete = True

    db.session.commit()

    return jsonify(ApiResponse.success())
@bp.route('/getAdminByMessage',methods=['POST'])
def getAdminByMessage():
    # 获取请求参数
    data = request.get_json()
    username = data.get('username')
    admin_is_banned = data.get('state')
    page = data.get('page')
    per_page = data.get('per_page')

    # 构建查询
    query = UserModel.query.filter_by(is_delete=False,state='3')

    # 根据存在的参数构建查询条件
    if username:
        query = query.filter(UserModel.username.ilike(f'%{username}%'))
    if admin_is_banned:
        query = query.filter(UserModel.state.ilike(f'%{admin_is_banned}%'))
    # 进行分页查询
    pagination = query.order_by(UserModel.id).paginate(page=page, per_page=per_page, error_out=False)

    # 获取分页数据
    items = pagination.items

    # 构造响应数据
    response_data = {
        'page': pagination.page,
        'per_page': pagination.per_page,
        'total': pagination.total,
        'pages': pagination.pages,
        'data': [item.to_dict() for item in items]  # 假设有一个to_dict方法来准备数据
    }
    return jsonify(ApiResponse.success(response_data))
@bp.route('/updateAdmin',methods=['POST'])
def updateAdmini():
    # 获取请求参数
    data = request.get_json()
    id = data['id']

    users = UserModel.query.filter_by(id = id,is_delete=False).first()
    if not users:
        return jsonify(ApiResponse.server_error("没有该admin"))

    if users.admin_is_banned:
        users.admin_is_banned = False
    else:
        users.admin_is_banned = True
    users.reset_time = datetime.now()
    db.session.commit()
    # 构造ApiResponse对象并返回
    return jsonify(ApiResponse.success())
@bp.route('/deleteAdmin',methods=['POST'])
def deleteAdmin():
    # 获取请求参数
    data = request.get_json()
    id = data['id']

    users = UserModel.query.filter_by(id = id,is_delete=False).first()
    if not users:
        return jsonify(ApiResponse.server_error("没有该admin"))

    users.is_delete = True
    db.session.commit()
    # 构造ApiResponse对象并返回
    return jsonify(ApiResponse.success())

@bp.route('/addAdmin',methods=['POST'])
def addAdmin():
    # 获取请求参数
    print(11111)
    data = request.get_json()
    username = data['username']
    password = data['password']

    users = UserModel.query.filter_by(username = username,is_delete=False).first()
    if users:
        return jsonify(ApiResponse.server_error("该admin已经存在"))
    password = md5_encrypt(password)
    user = UserModel(username=username,password=password,state='3')
    print(22222)
    db.session.add(user)
    db.session.commit()
    # 构造ApiResponse对象并返回
    return jsonify(ApiResponse.success())